package com.example.neteaseapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.neteaseapplication.entity.Song;
import com.example.neteaseapplication.service.MusicService;
import com.example.neteaseapplication.ui.home.LocalMusicAdapter;
import com.example.neteaseapplication.util.LocalMusicUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LocalMusicActivity extends Activity implements View.OnClickListener {

    private List<Song> mSongList = new ArrayList<>();
    private ListView mListView;
    private static final String TAG = "LocalMusicActivity";
    private ImageView mIvPlaying;
    private int flag = 0;
    private ImageView mIvMusicImg;
    private TextView mTvMusicName;
    private TextView mTvSingerName;
    private ImageButton mIbPrev;
    private ImageButton mIbPlay;
    private ImageButton mIbNext;
    private MusicService.MusicBinder mMusicBinder;
    private MusicConn mMusicConn;
    private Song mSong;
    private ImageButton ibBackHome;
    private int mCurrentIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//满屏显示
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        setAndroidNativeLightStatusBar(this, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_music);
        initView();
        check();
        Intent intentFromMain = getIntent();
        mSongList = intentFromMain.getParcelableArrayListExtra("songs");
        mCurrentIndex = intentFromMain.getIntExtra("CurrentIndex", 0);
        Log.e(TAG, mSongList.toString());
        LocalMusicAdapter localMusicAdapter = new LocalMusicAdapter(this, R.layout.music_item, mSongList);
        mListView.setAdapter(localMusicAdapter);
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
        mMusicConn = new MusicConn();
        bindService(intent, mMusicConn, BIND_AUTO_CREATE);

        if (mSongList == null) {

        } else {
            mSong = mSongList.get(mCurrentIndex);
        }
        initMusic(mSong);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSong = mSongList.get(position);
                mMusicBinder.start(mSong, LocalMusicActivity.this);
                flag = 1;
                mCurrentIndex = position;
                mIbPlay.setBackgroundResource(R.drawable.pause);
                mIvPlaying = view.findViewById(R.id.iv_is_playing);
                mTvMusicName.setText(mSong.getName());
                mTvSingerName.setText(mSong.getSinger());
                Bitmap bitmap = LocalMusicUtils.getArtwork(LocalMusicActivity.this, mSong.getId(), mSong.getAlbumId(), false, false);
                mIvMusicImg.setImageBitmap(bitmap);
            }
        });
    }

    /**
     * 动态授权
     */
    public void check() {
        if (ActivityCompat.checkSelfPermission(LocalMusicActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(LocalMusicActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        } else {
            Log.e(TAG, "已授权");

        }

    }

    public class MusicConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMusicBinder = (MusicService.MusicBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    /**
     * 初始化控件
     */
    public void initView() {
        mListView = findViewById(R.id.lv_local_music);
        mIvMusicImg = findViewById(R.id.iv_music_img);
        mTvMusicName = findViewById(R.id.tv_music_name_playing);
        mTvSingerName = findViewById(R.id.tv_music_singer_playing);
        mIbPrev = findViewById(R.id.ib_prev);
        mIbPlay = findViewById(R.id.ib_play_pause);
        mIbNext = findViewById(R.id.ib_next);
        ibBackHome = findViewById(R.id.ib_back_home);

        mIbPrev.setOnClickListener(this);
        mIbPlay.setOnClickListener(this);
        mIbNext.setOnClickListener(this);
        ibBackHome.setOnClickListener(this);
    }

    /**
     * 从本地查询音乐
     */
    /*public List<Song> queryMusic() {
        
//        mSongList = LocalMusicUtils.getmusic(this);
//        Log.e("TAG", mSongList.toString());
        return mSongList;
    }*/

    /**
     * 更改状态栏
     *
     * @param activity
     * @param dark
     */
    private static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    /**
     * 播放&暂停&上一首&下一首
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_prev:
//                int preNum = mSongList.indexOf(mSong);
                if (mCurrentIndex == 0) {
                    mSong = mSongList.get(mSongList.size() - 1);
                    mCurrentIndex = mSongList.size() - 1;
                } else {
                    mSong = mSongList.get(mCurrentIndex - 1);
                    mCurrentIndex--;
                }
                mMusicBinder.start(mSong, LocalMusicActivity.this);
                initMusic(mSong);
                mIbPlay.setBackgroundResource(R.drawable.pause);
                flag = 1;
                break;
            case R.id.ib_play_pause:

                if (flag == 1) {
                    mMusicBinder.pause();
                    mIbPlay.setBackgroundResource(R.drawable.play3);
                    flag = 0;
                } else {
                    mMusicBinder.start(mSong, LocalMusicActivity.this);
                    flag = 1;
                    mIbPlay.setBackgroundResource(R.drawable.pause);

                }
                break;
            case R.id.ib_next:
//                int nexNum = mSongList.indexOf(mSong);
                if (mCurrentIndex < mSongList.size() - 1) {
                    mSong = mSongList.get(mCurrentIndex + 1);
                    mCurrentIndex++;
                } else {
                    mCurrentIndex = 0;
                    mSong = mSongList.get(mCurrentIndex);
                }
                mMusicBinder.start(mSong, LocalMusicActivity.this);
                initMusic(mSong);
                mIbPlay.setBackgroundResource(R.drawable.pause);
                flag = 1;
                break;
            case R.id.ib_back_home:
                Intent intent = new Intent();
                intent.putExtra("mainId", mCurrentIndex);
                intent.setClass(LocalMusicActivity.this, MainActivity.class);
                startActivity(intent);
            default:
                break;
        }
    }

    public void toPlayingPage(View view) {
        Intent intent = new Intent();
        intent.putExtra("binder", mMusicBinder);
        int index = mSongList.indexOf(mSong);
        intent.putParcelableArrayListExtra("songs", (ArrayList<? extends Parcelable>) mSongList);
        Bundle bundle = new Bundle();
        bundle.putInt("id", index);
        intent.putExtras(bundle);
        intent.putExtra("song", mSong);
        startActivity(intent.setClass(LocalMusicActivity.this, MusicPlayingActivity.class));
    }

    /**
     * 默认第一首歌
     */
    public void initMusic(Song song) {
        mTvMusicName.setText(song.getName());
        mTvSingerName.setText(song.getSinger());
        Bitmap bitmap = LocalMusicUtils.getArtwork(LocalMusicActivity.this, song.getId(), song.getAlbumId(), false, false);
        mIvMusicImg.setImageBitmap(bitmap);
    }
}
